<!-- components/WxLoginButton.vue -->
<template>
  <button
    class="wx-login-btn"
    :style="customStyle"
    @tap="onLogin"
    :loading="loading"
    :disabled="loading"
  >
    <slot>{{ text }}</slot>
  </button>
</template>

<script>
import { login } from '@/api/auth'

export default {
  name: 'WxLoginButton',
  props: {
    text: {
      type: String,
      default: '微信一键登录'
    },
    customStyle: {
      type: String,
      default: ''
    }
  },
  emits: ['success', 'fail'],
  data() {
    return {
      loading: false
    }
  },
  methods: {
    async onLogin() {
      this.loading = true
      try {
        // 1. 获取微信登录code
        const loginRes = await uni.login({ provider: 'weixin' })
        if (!loginRes.code) throw new Error('获取code失败')
        
        // 2. 获取用户信息
        const userRes = await uni.getUserProfile({ desc: '用于完善会员资料' })
        
        // 3. 调用后端登录接口
        const res = await login({
          code: loginRes.code,
          userInfo: userRes.userInfo
        })
        
        // 4. 保存登录信息
        uni.setStorageSync('token', res.token)
        uni.setStorageSync('userInfo', res.userInfo)
        
        this.$emit('success', res)
      } catch (err) {
        console.error('Login failed:', err)
        this.$emit('fail', err)
      } finally {
        this.loading = false
      }
    }
  }
}
</script>

<style scoped>
.wx-login-btn {
  width: 100%;
  height: 88rpx;
  background: #07c160;
  color: #fff;
  font-size: 32rpx;
  border-radius: 44rpx;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  box-shadow: 0 4rpx 16rpx 0 rgba(7,193,96,0.12);
  transition: background 0.2s;
}
.wx-login-btn:active {
  background: #06ad56;
}
</style> 